#流程
#1.Connect wifi
#2.Create socket
#3.receive Udqp
#4.on/off led
import socket
import machine
import time
import network


#======================连接Wifi======================
def wifi_connect():
    wlan=network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect('Xiaomi_F627','12345678')
        i=1
        while not wlan.isconnected():
           print("正在连接网络。。。{}".format(i)) 
           time.sleep(1)#1s询问一次
    print('network config:',wlan.ifconfig())

#======================创建套接字======================
def create_udp_socket(): 
    udp_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp_socket.bind(("0.0.0.0",6789))
    return udp_socket
        


    
    
def main():   
    led = machine.Pin(2, machine.Pin.OUT)
    led.value(1)
    time.sleep(1)
    led.value(0)
    #1.Connect wifi
    wifi_connect()
    #2.Create socket
    udp_socket=create_udp_socket()
    #3.receive Udqp
    while True:
        recv_data, sender_info = udp_socket.recvfrom(1024)
        print("{}发送{}".format(sender_info, recv_data))
        recv_data_str = recv_data.decode("utf-8")
        try:
            print(recv_data_str)
        except Exception as ret:
            print("error:", ret)       
        # 处理接收的数据
        if recv_data_str == "light on":
            print("这里是要灯亮的代码...")
            led.value(1)
        elif recv_data_str == "light off":
            print("这里是要灯灭的代码...")
            led.value(0)
        elif recv_data_str == "light triggle":
            print("这里是要灯闪烁的代码...")
            for i in range(5) :
                led.value(1)
                time.sleep(0.5)
                led.value(0)
                time.sleep(0.5)
        
if __name__ == '__main__':
    main()
